package com.tianqu.tms.www.common.action;

import java.util.List;
import java.util.Locale;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tianqu.tms.core.taglib.MenuBean;
import com.tianqu.tms.core.util.MenuTagUtil;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsAction;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.base.UserContextImpl;
import com.tianqu.tms.core.exception.LoginException;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.www.common.actionform.LoginActionForm;
import com.tianqu.tms.www.common.controller.LoginController;
import org.apache.struts.action.ActionServlet;

/**
 * 登录Action
 *
 * @author liugang
 */
public class LoginAction extends TmsAction {

    private static final String SUCCESS = "TMSHome";
    private static final String TMSCARAUTOTERMINAL = "TMSCarAutoTerminal";
    private static final String REQUEST_PARAM_LANGUAGE = "language_choice";

    private Logger logger = Logger.getLogger(LoginAction.class);

    /**
     * @return
     */
    protected boolean isLogedIn() {
        return false;
    }

    /*
     * (non-Javadoc)
     * @see com.ibm.jp.ams.iris.core.action.IrisAction#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        logger.debug(this.getClass().getName() + "#execute was called.");
        ActionForward forward = null;
        UserContext uc = (UserContextImpl) request.getSession().getAttribute(TmsConstants.USER_CONTEXT_KEY);
        if (uc != null) {
            uc.clear();
            request.getSession().invalidate();
        }
        forward = super.execute(mapping, form, request, response);
        return forward;
    }

    /*
     * (non-Javadoc)
     * @see com.ibm.jp.ams.iris.core.action.IrisAction#doAction(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, com.ibm.jp.ams.iris.controller.UserContext)
     */
    protected ActionForward doAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                     HttpServletResponse response, UserContext uc) throws Exception {
        if (uc != null) {
            uc.clear();
            uc.setUserProfile(null);
        }
        HttpSession session = request.getSession(true);
        LoginActionForm loginForm = (LoginActionForm) form;

        logger.debug("Logging in with Test UserId: " + loginForm.getUserId());

        LoginController loginController = new LoginController();
        try {
            loginController.execute(uc);
        } catch (TmsException e) {
            //状態の変更
            if (e instanceof LoginException) {
                setErrorsToRequest(request, e.getExceptionId(), e.getErrorParams());
                return mapping.getInputForward();
            } else {
                throw e;
            }
        }

        // Locale设定
        selectLocale(request, uc);
        uc.setRootMenuBean(MenuTagUtil.getMenuBean(request));
        session.setAttribute(TmsConstants.USER_CONTEXT_KEY, uc);
        session.setAttribute(TmsAction.APPLICATION_USER_CONTEXT_KEY, uc);
        session.setAttribute("userName",uc.getUserProfile().getRealName());
        MenuTagUtil.setMenu(request, null);
        String menuFlag = (String) request.getParameter("menuFlag");
        if ("carAutoTerminal".equals(menuFlag)) {
            return mapping.findForward(TMSCARAUTOTERMINAL);
        } else {
            return mapping.findForward(SUCCESS);
        }
    }

    /**
     * 设置语言
     *
     * @param request
     * @param uc
     */
    private void selectLocale(HttpServletRequest request, UserContext uc) {

        Locale loc = getLocale(request);
        String lang = request.getParameter(REQUEST_PARAM_LANGUAGE);
        if (lang == null) {
            lang = uc.getUserProfile().getLocallangCode();
        }

        if ("en".equals(lang)) {
            loc = Locale.ENGLISH;
            logger.debug("locale set to " + loc);
        } else { // cn is default
            loc = Locale.CHINESE;
            logger.debug("locale set to " + loc);
        }

        setLocale(request, loc);
        uc.setLanguage(loc.getLanguage());
    }
}
